package com.hehe.httpurlconnectiontest2;

import android.util.Log;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by lenove on 2017/11/15.
 *
 * 这个类只用于用于http测试
 */

public class GetData {

        //定义一个获取网络图片数据的方法
        // path为我们要访问的URL
        public static byte[] getImage(String path) throws Exception{
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置连接超时为5秒
            conn.setConnectTimeout(5000);
            //设置请求类型为Get类型
            conn.setRequestMethod("GET");
            //判断请求url是否成功
            if (conn.getResponseCode() != 200){
                throw new RuntimeException("请求url失败");
            }
            InputStream inStream = conn.getInputStream();
            byte[] bt = StreamTool.read(inStream);
            inStream.close();
            return bt;
        }

        //获取网页的http源代码
        // path为我们要访问的URL
        public static String getHtml(String path) throws Exception{
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setRequestProperty("U-ApiKey","86d085fda02db25d2b48f25f5d9c7b8c");
            conn.setUseCaches(false);
            int response_code = conn.getResponseCode();
            Log.i("GetData.response",":"+response_code);
            if (response_code==200){
                InputStream in = conn.getInputStream();
                byte[] data = StreamTool.read(in);
                String html = new String(data,"UTF-8");
                Log.i("GetData.html",":"+html);
                return html;
            }else {
                return "5";
            }
        }

}
